<?php

class OrderAction extends PublicAction
{
    protected $sessionId;
    protected $cartModel;
    protected $userId;

    function _initialize()
    {
        parent::_initialize();
        $this->cartModel = M('Cart');
        $this->sessionId = cookie('onlineid');
        $this->userId =!empty($_SESSION['user']['id']) ? $_SESSION['user']['id'] : 0;
    }

    public function checkout()
    {
        $map['is_checked'] = 1;
        if ($this->userId) {
            $map['user_id'] = $this->userId;
        } else {
            $map['session_id'] = $this->sessionId;
        }

        $cart = $this->cartModel->where($map)->select();
        if (empty($cart)) {
            $this->error('您的购物车中没有商品！');
        }

        $amount = 0;

        foreach ($cart as $key => $r) {
            $amount = $amount + $r['price'];
        }

        $this->assign('cart', $cart);

        //送货方式
        $shipping = M('Shipping')->where("status=1")->select();

        //收货地址
        $area = M('Area')->getField('id,name');
        $user_address = '';
        $default_address = array();  //默认收货地址
        if ($this->userId) {
            $user_address = M('UserAddress')->where("user_id='{$this->userId}'")->select();
            foreach ($user_address as $addr) {
                if ($addr['is_default'] == 1) $default_address = $addr;
            }
        }

        $this->assign('user_address', $user_address);
        $this->assign('default_address', $default_address);
        $this->assign('area', $area);
        $this->assign('shipping', $shipping);

        if ($this->userId) {
            $this->display();
        } else {
            $this->display('Order:checkout_nologin');
        }
    }

    //寄送
    function delivery()
    {
        if (IS_POST) {
            $_POST['user_id'] = $_SESSION['user']['id'];

            $row = M('consignees')->add($_POST);
            if ($row) {
                $this->success('添加成功！', '', 1);
            }
        }
    }

    public function check()
    {
        //检查购物车中是否有商品
        $cart_count = $this->cartModel->where("user_id = '$this->userId'")->count();
        if ($cart_count == 0) {
            $this->error('您的购物车为空!');
        }
        $order = array();
        if ($this->userId) {

            //检测收货人信息
            $addressId = I('address_id', 0, 'intval');
            if (!$addressId) {
                $this->error('请选择收货地址!');
            }

            $address = M('UserAddress')->where('id=' . $addressId)->find();

            if (!$address) {
                $this->error('非法参数！');
            }

            $order['consignee'] = $address['consignee'];
            $order['country'] = intval($address['country']);
            $order['province'] = intval($address['province']);
            $order['city'] = intval($address['city']);
            $order['area'] = intval($address['area']);
            $order['address'] = $address['address'];
            $order['zipcode'] = $address['zipcode'];
            $order['tel'] = $address['tel'];
            $order['mobile'] = $address['mobile'];
            $order['email'] = $address['email'];
        } else {
            $order['province'] = I('province', 0, 'intval');
            if (empty($order['province'])) {
                $this->error('请选择省份!');
            }
            $order['city'] = I('city', 0, 'intval');
            if (empty($order['city'])) {
                $this->error('请选择城市!');
            }
            $order['area'] = I('area', 0, 'intval');
            if (empty($order['area'])) {
                $this->error('请选择区域!');
            }
            $order['address'] = I('address');
            if (empty($order['address'])) {
                $this->error('请填写详细地址!');
            }

            $order['consignee'] = I('consignee');
            if (empty($order['consignee'])) {
                $this->error('请填写收货人!');
            }
            $order['zipcode'] = I('zipcode');
            if (empty($order['zipcode'])) {
                $this->error('请填写邮编!');
            }

            $order['tel'] = I('tel');
            $order['mobile'] = I('mobile');
            if (empty($order['mobile'])) {
                $this->error('请填写手机号码!');
            }
            $order['email'] = I('consignee_email');
        }

        /*商品金额*/
        if ($this->userId) {
            $cart = $this->cartModel->where("user_id='{$this->userId}'")->select();
        } else {
            $cart = $this->cartModel->where("session_id='{$this->sessionId}'")->select();
        }

        $amount = 0;
        foreach ($cart as $key => $r) {
            $amount = $amount + $r['price'];
        }

        /*配送方式*/
        $shippingId = intval($_POST['shipping_id']);
        $Shipping = M('Shipping')->find($shippingId);

        /*保价*/
        if (intval($_POST['isinsure'])) {
            $insure_fee = $amount * $Shipping['insure_fee'] / 100;
            $insure_fee = number_format($insure_fee, 2);
            if ($insure_fee <= $Shipping['insure_low_price']) {
                $insure_fee = $Shipping['insure_low_price'];
            }

            $order['insure_fee'] = $insure_fee;
        }

        /*支付方式*/
        $payment = I('post.payment', '', 'trim');
        if (!$payment) {
            $this->error('请选择支付方式');
        }

        /*发票*/
        $order['invoice'] = intval($_POST['invoice']);
        if ($order['invoice']) {
            $order['invoice_title'] = htmlspecialchars($_POST['invoice_title']);
            $order['invoice_fee'] = $amount * $_POST['invoice_fee'] / 100;
            $order['invoice_fee'] = number_format($order['invoice_fee'], 2);
        }

        $order['amount'] = $amount;

        $order['shipping_fee'] = number_format($Shipping['first_price'], 2);
        $order['order_amount'] = $order['amount'] + $order['invoice_fee'] + $order['insure_fee'] + $order['shipping_fee'];

        $order['user_id'] = $this->userId;
        $order['order_status'] = 0;
        $order['pay_status'] = 0;
        $order['shipping_status'] = 0;

        $order['shipping_id'] = intval($Shipping['id']);
        $order['shipping_name'] = $Shipping['name'] ? $Shipping['name'] : '';

        $order['pay_name'] = $payment;
        $order['pay_code'] = $payment;
        $order['postmessage'] = htmlspecialchars($_POST['postmessage']);

        $order['add_time'] = time();

        foreach ($order as $key => $r) {
            if ($r == null) $order[$key] = '';
        }

        $order_db = M('Order');

        $orderId = $order_db->add($order);

        if ($orderId) {
            $order['order_sn'] = date("Ymd") . sprintf('%06d', $orderId);
            $order_db->save(array('id' => $orderId, 'order_sn' => $order['order_sn']));
            foreach ($cart as $key => $r) {
                $cart[$key]['order_id'] = $orderId;
                $cart[$key]['user_id'] = $this->userId;
                M('OrderData')->add($cart[$key]);
            }
            //删除购物车信息
            $this->cartModel->where("user_id = '$this->userId'")->delete();
        }

        $data = array('status' => 1, 'info' => '下单成功！', 'url' => '/Order/done/id/' . authcode($orderId,'ENCODE'));
        $this->ajaxReturn($data);
    }


    public function done()
    {
        $orderId = I('id', 0, 'trim');
        $orderId = authcode($orderId);
        $order = M('Order')->where('id=' . $orderId)->find();
        if (!$order) {
            $this->redirect('/');
        }
        $this->assign('order', $order);
        $this->display();
    }

    public function pay()
    {
        $orderId = I('order_id', 0 ,'intval');
        $order = M('Order')->where('id=' . $orderId)->find();
        $data['out_trade_no'] = $order['order_sn'];
        $orderData = M('Order_data')->where('order_id=' . $orderId)->select();

        foreach ($orderData as $val) {
            $data['subject'] .= $val['product_name'] . ' ';
        }
        $data['price'] = $order['order_amount'];
//        $data['price'] = '0.01';
        $data['body'] = $order['consignee'] . ' ' . $order['postmessage'];

        if ($order['pay_code'] == 'alipay') {
            alipay($data);
        } else {
            $data = array(
                'body' => $data['subject'],
                'total_fee' => $data['price']*100,
                'out_trade_no' => $data['out_trade_no'],
                'product_id' => (int)$orderData[0]['product_id']
            );
            weixinpay($data);
        }
    }

    public function query()
    {
        if (I('get.order_sn')) {
            $sn = I('get.order_sn');
            unset($_GET['order_sn']);
        }

        if (!empty($this->userId) || !empty($sn)) {

            $map['user_id'] = intval($this->userId);

            if ($sn) {
                $map['order_sn'] = $sn;
            }

            $order_db = M('Order');

            if (isset($_GET['order'])) {
                $order = $_GET ['order'];
            } else {
                $order = !empty($sortBy) ? $sortBy : 'id';
            }

            if (isset($_GET['sort'])) {
                $_GET['sort'] == 'asc' ? $sort = 'asc' : $sort = 'desc';
            } else {
                $sort = $asc ? 'asc' : 'desc';
            }

            $_REQUEST['sort'] = $sort;
            $_REQUEST['order'] = $order;
            $keyword = $_REQUEST['keyword'];
            $searchtype = $_REQUEST['searchtype'];

            if (!empty($keyword) && !empty($searchtype)) {
                $map[$searchtype] = array('like', '%' . $keyword . '%');
            }

            foreach ($_REQUEST['map'] as $key => $res) {
                if (($res === '0' || $res > 0) || !empty($res)) {
                    if ($_REQUEST['maptype'][$key]) {
                        $map[$key] = array($_REQUEST['maptype'][$key], $res);
                    } else {
                        $map[$key] = intval($res);
                    }
                    $_REQUEST[$key] = $res;
                } else {
                    unset($_REQUEST[$key]);
                }
            }
            $this->assign($_REQUEST);

            //取得满足条件的记录总数
            $count = $order_db->where($map)->count('id');//echo $model->getLastsql();

            if ($count > 0) {
                import("@.ORG.Page");

                $p = new Page($count, 10);

                //分页查询数据
                $list = $order_db->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
                foreach ($list as $key => $val) {
                    $list[$key]['order_data'] = M('OrderData')->where('order_id=' . $val['id'])->select();
                }

                //分页跳转的时候保证查询条件
                foreach ($map as $key => $val) {
                    if (!is_array($val)) {
                        $p->parameter .= "$key=" . urlencode($val) . "&";
                    }
                }
                //分页显示
                $page = $p->show();

                //模板赋值显示
                $this->assign('list', $list);
                $this->assign('page', $page);
            }
        }
        $this->display();
    }

    public function orderList()
    {
        $map['user_id'] = session('user.id');


        $tabCode = I('tabCode','', 'trim');
        if ($tabCode == 'waitPay') {
            $map['order_status'] = 0;
        }
        if ($tabCode == 'waitSend') {
            $map['pay_status'] = 2;
            $map['shipping_status'] = 0;
        }
        if ($tabCode == 'waitConfirm') {
            $map['shipping_status'] = 1;
        }

        if ($tabCode == 'waitRate') {
            $map['shipping_status'] = 2;
            $map['shipping_status'] = 0;
        }

        $order_db = M('Order');

        if (isset($_GET['order'])) {
            $order = $_GET ['order'];
        } else {
            $order = !empty($sortBy) ? $sortBy : 'id';
        }

        if (isset($_GET['sort'])) {
            $_GET['sort'] == 'asc' ? $sort = 'asc' : $sort = 'desc';
        } else {
            $sort = 'desc';
        }

        $_REQUEST['sort'] = $sort;
        $_REQUEST['order'] = $order;

        if (!empty($keyword) && !empty($searchtype)) {
            $map[$searchtype] = array('like', '%' . $keyword . '%');
        }

        foreach ($_REQUEST['map'] as $key => $res) {
            if (($res === '0' || $res > 0) || !empty($res)) {
                if ($_REQUEST['maptype'][$key]) {
                    $map[$key] = array($_REQUEST['maptype'][$key], $res);
                } else {
                    $map[$key] = intval($res);
                }
                $_REQUEST[$key] = $res;
            } else {
                unset($_REQUEST[$key]);
            }
        }
        $this->assign($_REQUEST);

        //取得满足条件的记录总数
        $count = $order_db->where($map)->count('id');//echo $model->getLastsql();

        if ($count > 0) {
            import("@.ORG.Page");

            $p = new Page($count, 10);

            //分页查询数据
            $list = $order_db->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
            foreach ($list as $key=>$val) {
                $list[$key]['order_data'] = M('OrderData')->where('order_id='.$val['id'])->select();
            }

            //分页跳转的时候保证查询条件
            foreach ($map as $key => $val) {
                if (!is_array($val)) {
                    $p->parameter .= "$key=" . urlencode($val) . "&";
                }
            }
            //分页显示
            $page = $p->show();

            //模板赋值显示
            $this->assign('list', $list);
            $this->assign('page', $page);
        }

        $this->display();
    }

    public function detail()
    {
        $sn = I('order_sn', '', 'trim');
        $id = I('id', 0, 'intval');
        $order_db = M('Order');
        $order = $id ? $order_db->find($id) : $order_db->getByOrderSn($sn);
        if (!$order) {
            $this->success(L('do_empty'));
        }

        $order_data = M('OrderData')->where("order_id='{$order['id']}'")->select();

        $amount = 0;
        foreach ($order_data as $key => $r) {
            $amount = $amount + $r['price'];
        }

        $Shipping = M('Shipping')->find($shippingid);
        $area = M('Area')->getField('id,name');
        $this->assign('area', $area);
        $this->assign('Payment', $Payment);
        $this->assign('Shipping', $Shipping);

        $this->assign('order', $order);
        $this->assign('order_data', $order_data);
        $this->assign('amount', $amount);
        $this->display();
    }

    function ajax()
    {
        $model = M('Order');
        $order = $model->find($_POST['id']);
        if ($order['user_id'] != $this->userId) {
            die(json_encode(array('msg' => L('do_empty'))));
        }
        if ($_GET['do'] == 'saveaddress') {
            $model->save($_POST);
            die(json_encode(array('id' => 1)));
        } elseif ($_GET['do'] == 'order_status') {
            $_POST['status'] = 3;
            $_POST['confirm_time'] = time();
            $model->save($_POST);
            die(json_encode(array('id' => 1)));
        } elseif ($_GET['do'] == 'pay_status') {
            $_POST['pay_status'] = 3;
            $model->save($_POST);
            die(json_encode(array('id' => 1)));
        } elseif ($_GET['do'] == 'shipping_status') {
            $_POST['shipping_status'] = $_POST['num'];
            unset($_POST['num']);
            $_POST['accept_time'] = $_POST['shipping_status'] == 2 ? time() : '';
            $model->save($_POST);
            die(json_encode(array('id' => 1)));
        }
    }
}